﻿using System;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Nop.Core.Domain.Tasks;
using Nop.Plugin.Misc.DynamicsCrm.Models;
using Nop.Plugin.Misc.DynamicsCrm.Services;
using Nop.Services.Configuration;
using Nop.Services.Localization;
using Nop.Services.Tasks;
using Nop.Web.Framework.Controllers;

namespace Nop.Plugin.Misc.DynamicsCrm.Controllers
{
    [AdminAuthorize]
    public class SettingsController : Controller
    {
        private const string VIEW_PATH = "Nop.Plugin.Misc.DynamicsCrm.Views.Settings.Index";
        private readonly IDynamicsCrmApiService _dynamicsCrmApiService;
        private readonly IScheduleTaskService _scheduleTaskService;
        private readonly ISettingService _settingService;
        private readonly ILocalizationService _localizationService;
        private readonly DynamicsCrmSettings _settings;
        private readonly IDynamicsCrmEventQueueingService _subscriptionEventQueueingService;

        public SettingsController(ISettingService settingService, IScheduleTaskService scheduleTaskService, 
            IDynamicsCrmApiService dynamicsCrmApiService, IDynamicsCrmEventQueueingService subscriptionEventQueueingService, 
            ILocalizationService localizationService, DynamicsCrmSettings settings)
        {
            this._settingService = settingService;
            this._scheduleTaskService = scheduleTaskService;
            this._dynamicsCrmApiService = dynamicsCrmApiService;
            this._subscriptionEventQueueingService = subscriptionEventQueueingService;
            this._localizationService = localizationService;
            this._settings = settings;
        }



        [NonAction]
        private DynamicsCrmSettingsModel PrepareModel()
        {
            var model = new DynamicsCrmSettingsModel();

            //Set the properties
            model.UserName = _settings.UserName;
            model.OrganizationUri = _settings.OrganizationUri;
            model.EmailErrorsTo = _settings.EmailErrorsTo;
            model.Password = _settings.Password;
            model.CustomerTypeCode = _settings.CustomerTypeCode;
            model.PriceLevel = _settings.PriceLevel;
            model.Uom = _settings.Uom;
            model.UomSchedule = _settings.UomSchedule;
            ScheduleTask task = FindScheduledTask();
            if (task != null)
            {
                model.AutoSyncEachMinutes = task.Seconds / 60;
                model.AutoSync = task.Enabled;
            }

            return model;
        }

        [NonAction]
        private ScheduleTask FindScheduledTask()
        {
            return _scheduleTaskService.GetTaskByType("Nop.Plugin.Misc.DynamicsCrm.DynamicsCrmSynchronizationTask, Nop.Plugin.Misc.DynamicsCrm");
        }

        public ActionResult Index()
        {
            var model = PrepareModel();
            //Return the view
            return View(VIEW_PATH, model);
        }

        [HttpPost]
        [FormValueRequired("save")]
        public ActionResult Index(DynamicsCrmSettingsModel model)
        {
            string saveResult = "";
            if (ModelState.IsValid)
            {
                _settings.OrganizationUri = model.OrganizationUri;
                _settings.UserName = model.UserName;
                _settings.Password = model.Password;
                _settings.EmailErrorsTo = model.EmailErrorsTo;
                _settings.CustomerTypeCode = model.CustomerTypeCode;
                _settings.PriceLevel = model.PriceLevel;
                _settings.Uom = model.Uom;
                _settings.UomSchedule = model.UomSchedule;


                _settingService.SaveSetting(_settings);
            }

            // Update the task
            var task = FindScheduledTask();
            if (task != null)
            {
                task.Enabled = model.AutoSync;
                task.Seconds = model.AutoSyncEachMinutes*60;
                _scheduleTaskService.UpdateTask(task);
                saveResult = _localizationService.GetResource("Plugin.Misc.DynamicsCrm.AutoSyncRestart");
            }

            model = PrepareModel();
            //set result text
            model.SaveResult = saveResult;

            return View(VIEW_PATH, model);
        }

        [HttpPost, ActionName("Index")]
        [FormValueRequired("queueallcontacts")]
        public ActionResult QueueAllContacts()
        {
            _subscriptionEventQueueingService.QueueAllContacts();

            return Index();
        }


        [HttpPost, ActionName("Index")]
        [FormValueRequired("queueallorders")]
        public ActionResult QueueAllOrders()
        {
            _subscriptionEventQueueingService.QueueAllOrders();

            return Index();
        }


        [HttpPost, ActionName("Index")]
        [FormValueRequired("sync")]
        public ActionResult Sync()
        {
            var model = PrepareModel();
            try
            {

                var result = _dynamicsCrmApiService.Synchronize();

                //set result text
                model.SyncResult = result.ToHtml();
            }
            catch (Exception exc)
            {
                //set result text
                model.SyncResult = exc.ToString();
            }
            
            return View(VIEW_PATH, model);
        }
    }
}